package solutions.leetcode.normal;

import solutions.lib.BaseSolution;

import java.util.Stack;

/**
 * @author lizhidong
 * <a href="https://leetcode-cn.com/problems/check-if-word-is-valid-after-substitutions/">1003. 检查替换后的词是否有效</a>
 */
public class Solution1003 extends BaseSolution {

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0, len = s.length(); i < len; i++) {
            char n = s.charAt(i);
            if (n != 'c') {
                stack.push(n);
                continue;
            }
            if (stack.size() < 2) {
                continue;
            }
            char ctop = stack.pop();
            char cnext = stack.peek();
            if (cnext == 'a' && ctop == 'b') {
                stack.pop();
            } else {
                return false;
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        Solution1003 solution = new Solution1003();
    }
}